using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Factory:Mob {

	[SerializeField] GameObject[] prefabs;
	[SerializeField] float spawnInterval = 3;
	float timeAfterSpawn;

	protected override void StateIdle() {
		if(HP<maxHP*0.5f) GoExploding();
	}

	void GoExploding() {
		stateTime=0;
		currentState=StateExploding;
	}

	Vector2 shakeOffset;

	void StateExploding() {

		if(stateTime>4f) {
			for(int i = 0;i<10;i++) {
				CreateOneMinion(transform.position,1);
			}
			Destroy(gameObject);
			return;
		}

		transform.localScale=Vector3.one*(1+stateTime*0.15f);

		Vector2 previousShakeOffset = shakeOffset;
		shakeOffset+=Random.insideUnitCircle*stateTime;
		shakeOffset=Vector2.ClampMagnitude(shakeOffset,0.05f);
		transform.position+=(Vector3)(shakeOffset-previousShakeOffset);

	}

	protected override void FixedUpdate() {
		base.FixedUpdate();
		timeAfterSpawn+=deltaTime;
		if(timeAfterSpawn>spawnInterval) {
			timeAfterSpawn-=spawnInterval;
			Mob target = Utility.FindNearestMob(
				position,
				25,
				(x) => {
					if(FactionManager.GetRelation(faction,x.faction)>=0) return false;
					return true;
				}
			);
			if(!target) return;
			CreateOneMinion(target.position,5);

		}
	}

	void CreateOneMinion(Vector2 centerposition,float spawnRadius) {
		for(int _ = 0;_<100;_++) {
			Vector2 position = centerposition+Random.insideUnitCircle*spawnRadius;
			if(TilemapController.SolidAt(position)) continue;
			if(!Utility.IfLineOfSight(centerposition,position)) continue;

			int index = Random.Range(0,prefabs.Length);
			Mob created = Instantiate(prefabs[index],transform.position,Quaternion.identity,transform.parent).GetComponent<Mob>();
			created.faction=faction;
			break;

		}
	}

}
